<?php

// include necessary files
include_once(dirname(__FILE__).'/schedulerConfig.php');
include_once(dirname(__FILE__).'/schedulerJob.php');

class Scheduler {
	
	/**
	 * Add job into scheduler
	 **/
	public function Add($object) {
	
		$objectSerialize = '"'.mysql_real_escape_string(serialize($object)).'"';
		$timeCreate = time();
		
		$SQL = "INSERT INTO scheduler (
			objectSerialize, timeCreate
			) VALUES (
			$objectSerialize, $timeCreate
			)";
		
		try {
			$this->Database_Exec($SQL);
		} catch (Exception $e) {
			// error handling
			throw $e;
		}
	}
	
	/**
	 * Run all new job
	 **/
	public function Start() {
		
		// get new jobs
		$result = $this->Database_Query('
			SELECT * FROM scheduler
			WHERE timeExecuted = 0
			');
			
		foreach ($result as $row) {
		
			$id = $row['id'];
			$exceptionMessage = '""';
			$timeExecuted = time();
			
			// run job
			try {
				$o = unserialize($row['objectSerialize']);
			} catch (Exception $e) {
				$exceptionMessage = $e->getMessage();
				$exceptionMessage = '"'.mysql_real_escape_string($exceptionMessage).'"';
			}
			
			// update job information
			$SQL = "
				UPDATE scheduler
				SET 
					 exceptionMessage = $exceptionMessage
					,timeExecuted = $timeExecuted
				WHERE id = $id
				";
			try {
				$this->Database_Exec($SQL);
			} catch (Exception $e) {
				// error handling
				throw $e;
			}
		}
	}
	
	public function __construct() {
		$this->Database_Open();
	}
	
	/**
	 * Open database connection
	 **/
	
	private function Database_Open() {
		if (!mysql_connect(
			 $_SERVER['Scheduler.Database.MySQL.Server']
			,$_SERVER['Scheduler.Database.MySQL.UserName']
			,$_SERVER['Scheduler.Database.MySQL.Password']
			)) {
			throw new Exception('Can not connect to database');
		}
		if (!mysql_select_db($_SERVER['Scheduler.Database.MySQL.Database'])) {
			throw new Exception('Can not open database');
		}
		return true;
	}
	
	/**
	 * Close database connection
	 **/
	
	private function Database_Close() {
		mysql_close();
	}
	
	/**
	 * Execute SQL statement
	 **/
	
	private function Database_Exec($SQL) {
		if (mysql_query($SQL)) { return true; }
		throw new Exception(mysql_error()."\n$SQL\n");
	}
	
	/**
	 * Execute SQL statement, return all rows as an array
	 **/
	
	private function Database_Query($SQL) {
		$result = array();
		if (!$query = mysql_query($SQL)) { return $result; }
		while ($row = mysql_fetch_assoc($query)) {
			$result[] = $row;
		}
		return $result;
	}
}

// running from console
if (!count(debug_backtrace()) {
	
	$className = basename(__FILE__,".php");
	
	while (true) {
		$object = new $className;
		$object->Start();
		sleep($_SERVER['Scheduler.Wait']);
	}
}
